import React, { useEffect, useRef, useState, useCallback } from "react";
import { SwiperSlide } from 'swiper/react';
import axios from "../../utils/http"
import PopShow from "./popShow"; // 弹出层评论
import Fun from "./Fun"; // 右下
import { Ellipsis } from 'antd-mobile'

// 中间
const Middle = React.memo(() => {
    return <>
        <img src="../yzh-imgs/voice_play.png" alt="暂停" className="voice_play" />
    </>
})

// 顶部
const Top = React.memo(() => {
    return <>
        <div className="tops">
            <div className="changeTop">
                <p>关注</p>
                <p>推荐</p>
            </div>
            <div className="sou">
                <img src="../yzh-imgs/搜索.png" />
            </div>
        </div>
    </>
})
// 左下
const User = React.memo((props) => {
    return <>
        <div className="user">
            <p className="p1">
                @{props.items.users[0].username}
            </p>
            <div className="p2">
                <Ellipsis direction='end' content={props.items.describe} />
            </div>
        </div>
    </>
})

// 视频模式
const VideoSlide = (props) => {
    const videoRef = useRef(null);
    const [videoFlag, setVideoFlag] = useState(false) // 是否暂停播放
    const [showIconPosition, setShowIconPosition] = useState(false) // 控制评论
    const { item, index, activeIndex } = props
    const [commentList, setCommentList] = useState([])
    const [commentCount, setCommentCount] = useState('')
    const [videoLoaded, setVideoLoaded] = useState(false); // 控制视频是否已经加载
    const [videoUrl, setVideoUrl] = useState('');
    const { _id } = JSON.parse(localStorage.getItem("user"))[0] || ""
    

    // 网络连接状态的变化处理
    const checkNetwork = () => {
        const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
        if (connection) {
            const { effectiveType } = connection;
            if (effectiveType === '2g' || effectiveType === 'slow-2g') {
                setVideoUrl(item.videoUrl[1]); // 网络较差时加载压缩版视频
            } else {
                setVideoUrl(item.videoUrl[0]); // 否则加载原视频
            }
        } else {
            // 如果浏览器不支持 connection API，默认加载原视频
            setVideoUrl(item.videoUrl[0]);
        }
    };

    // 是否播放
    const togglePlay = () => {
        if (videoRef.current.paused) {
            videoRef.current.play(); // 播放
            setVideoFlag(false)
        } else {
            videoRef.current.pause(); // 暂停
            setVideoFlag(true)
        }
    };

    // 添加父级评论
    const addComment = useCallback(async (val) => {
        const obj = {
            userId: _id, // 用户id
            videoId: item._id, // 视频id
            content: val, // 内容
            created_at: Date.now(), // 评论时间
        }
        const data = await axios.post("/yzh/addComment", obj)
        if (data.code == 200) {
            getComment(item._id)
            getCommentList(item._id)
        } else {
            console.log("错误了");
        }
    })

    // 获取当前评论数量
    const getComment = async (ids) => {
        try {
            const data = await axios.get("/yzh/getComment", {
                params: {
                    videoId: ids
                }
            })
            const { commentCount } = data
            // console.log(commentCount);

            setCommentCount(commentCount)
        } catch (err) {
            console.log(err);
        }
    }
    // 获取当前父评论数据
    const getCommentList = useCallback(async (ids) => {
        try {
            const data = await axios.post("/yzh/getCommentList", { videoId: ids })
            const { commentList } = data
            // console.log(commentList);
            setCommentList(commentList)
        } catch (err) {
            console.log(err);
        }
    })

    // 控制是否显示评论
    const setPink = useCallback((val) => {
        setShowIconPosition(val)
    })

    // 组件首次渲染时以及网络状态变化时执行
    useEffect(() => {
        checkNetwork();  // 初始时判断一次
        const handleConnectionChange = () => {
            checkNetwork(); // 网络状态变化时重新判断
        };

        // 监听网络状态变化
        const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
        if (connection) {
            connection.addEventListener('change', handleConnectionChange);
        }

        // 清理函数：移除事件监听
        return () => {
            if (connection) {
                connection.removeEventListener('change', handleConnectionChange);
            }
        };
    }, [item]);

    // 使用IntersectionObserver来懒加载视频
    useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        // 视频进入视口时，加载视频并播放
                        setVideoLoaded(true);
                        observer.disconnect(); // 加载完视频后停止观察
                    }
                });
            },
            { threshold: 0.10 } // 当视频有25%进入视口时开始加载
        );

        if (videoRef.current) {
            observer.observe(videoRef.current);
        }

        return () => {
            if (videoRef.current) {
                observer.unobserve(videoRef.current); // 清除观察
            }
        };
    }, []);

    // 控制视频播放状态
    useEffect(() => {
        getComment(item._id);
        if (activeIndex === index) {
            // 当前视频为活动状态，播放
            if (videoLoaded && videoRef.current) {
                videoRef.current.play();
                setVideoFlag(false);
            }
        } else {
            // 其他视频暂停
            if (videoRef.current) {
                videoRef.current.pause();
                setVideoFlag(true);
            }
        }
    }, [activeIndex, index, videoLoaded, commentCount]);

    return (
        <>
            <SwiperSlide>
                <div className="video-container swiper-slide">
                    <Top />
                    <User items={item} />
                    <Fun setPink={setPink} getCommentList={getCommentList} items={item} commentCount={commentCount} />
                    {
                        videoFlag ? <Middle /> : null
                    }
                    {/* 播放视频 */}
                    <video
                        ref={videoRef}
                        className="video"
                        src={videoLoaded ? videoUrl : ""}
                        controls={false} // 如果不希望显示浏览器默认控件，则设置为false
                        muted={false} // 静音
                        onClick={() => togglePlay()}
                        loop // 循环播放
                    >
                        您的浏览器不支持HTML5视频。
          </video>
                </div>
                <PopShow
                    showIconPosition={showIconPosition}
                    setPink={setPink}
                    commentCount={commentCount}
                    commentList={commentList}
                    items={item}
                    addComment={addComment}
                />
            </SwiperSlide>
        </>
    );
}


export default VideoSlide